import axios from 'axios'
import {getToken} from '@/utils/auth'
import {ElMessage} from 'element-plus'
import merge from 'lodash/merge'
import qs from 'qs'

const baseURL = import.meta.env.VITE_BASE_URL
const request = axios.create({
  baseURL,
  timeout: 20 * 1000 // 请求出错时间
})
let store = { getters: { token: 11 } }
// 添加请求拦截器，在请求头中加token
request.interceptors.request.use(
  config => {
    // 是否需要防止数据重复提交
    // const isRepeatSubmit = (config.headers || {}).repeatSubmit === false
    if (getToken()) {
      // config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      config.headers['session-key'] = getToken()
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 拦截器实现
request.interceptors.response.use(
  res => {
    const code = res.data.code || 200;
    return res.data
    // if (res.status === 200 && res.data.code === '000008') {
    // }
  },
  error => {
    ElMessage({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * get请求参数处理
 * @param {*} params 参数对象
 * @param {*} openDefultParams 是否开启默认参数?
 */
request.addParam = (params = {}, openDefultParams = true) => {
    let defaults = {
        't': new Date().getTime()
    }
    return openDefultParams ? merge(defaults, params) : params
}

/**
 * post请求数据处理
 * @param {*} data 数据对象
 * @param {*} openDefultdata 是否开启默认数据?
 * @param {*} contentType 数据格式
 *  json: 'application/json; charset=utf-8'
 *  form: 'application/x-www-form-urlencoded; charset=utf-8'
 */
request.addData = (data = {}, openDefultdata = true, contentType = 'json') => {
    if (!(data instanceof Array)) {
        let defaults = {
            't': new Date().getTime()
        }
        data = openDefultdata ? merge(defaults, data) : data
    }
    return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export default request
